<?php

use App\Models\Account;
use App\Models\User;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

/*
 * 声明gzip压缩数据
 * */

function gzipReturn($content) // $content 就是要压缩的页面内容，或者说饼干原料
{
    $rt = [
        'status' => 1,
        'msg' => '操作成功',
        'data' => $content
    ];

    $rt = json_encode($rt, JSON_UNESCAPED_UNICODE);

    header('Content-Type:application/json; charset=utf-8');

    if (
        !headers_sent() && // 如果页面头部信息还没有输出
        extension_loaded("zlib") && // 而且zlib扩展已经加载到PHP中
        strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")
    ) //而且浏览器说它可以接受GZIP的页面
    {
        $rt = gzencode($rt);
        //为准备压缩的内容贴上“//此页已压缩”的注释标签，然后用zlib提供的gzencode()函数执行级别为9的压缩，这个参数值范围是0-9，0表示无压缩，9表示最大压缩，当然压缩程度越高越费CPU。
        //然后用header()函数给浏览器发送一些头部信息，告诉浏览器这个页面已经用GZIP压缩过了！
        header("Content-Encoding: gzip");
        header("Vary: Accept-Encoding");
        header("Content-Length: " . strlen($rt));
    }
    exit($rt); //返回压缩的内容，或者说把压缩好的饼干送回工作台。
}

function success($data = null, $msg = '操作成功')
{
    $rt = [
        'code' => 0,
        'msg' => $msg,
        'data' => $data
    ];
    return response()->json($rt, 200)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    //header('Content-Type:application/json; charset=utf-8');
    //exit(json_encode($rt, JSON_UNESCAPED_UNICODE));
}

function fail($msg = '出错了', $code = -1)
{
    $rt = [
        'code' => $code,
        'msg' => $msg,
        'data' => null
    ];
    return response()->json($rt, 200)->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    // header('Content-Type:application/json; charset=utf-8');
    // exit(json_encode($rt, JSON_UNESCAPED_UNICODE));
}

//生成随机字符串
function strRandom($length = 6)
{
    $code = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
    $rand = $code[rand(0, 25)] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(true), 2, 5) . sprintf('%02d', rand(0, 99));
    for (
        $a = md5($rand, true),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
        $d = '',
        $f = 0;
        $f < $length;
        $g = ord($a[$f]), // ord（）函数获取首字母的 的 ASCII值
        $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F], //按位亦或，按位与。
        $f++
    );
    return $d;
}

function numberRandom()
{
    $used = User::pluck('invite_code')->toArray();
    $used[] = 1230;
    $area = array_values(array_diff(range(1000, 9999), $used));
    if (!$area) {
        $area = array_values(array_diff(range(1000, 99999), $used));
    }
    if (!$area) {
        $area = array_values(array_diff(range(1000, 999999), $used));
    }
    return $area[rand(0, count($area) - 1)];
}

function todayTimestamp()
{
    $start_time = date('Y-m-d H:i:s', strtotime(date('Y-m-d', time())));
    $end_time   = date('Y-m-d H:i:s', strtotime($start_time . '+1 day'));
    return [$start_time, $end_time];
}

function mobileFormat($mobile)
{
    return substr_replace($mobile, '****', 3, 4);
}

function getMobile()
{
    $map = [
        130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
        144, 147,
        150, 151, 152, 153, 155, 156, 157, 158, 159,
        176, 177, 178,
        180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
    ];
    return $map[array_rand($map)] . mt_rand(1000, 9999) . mt_rand(1000, 9999);
}

function writeLog($msg)
{
    Log::channel('test')->info($msg . PHP_EOL);
}

function weekInYear()
{
    $time = Carbon::now();
    return $time->weekYear() . $time->weekOfYear;
}

function lastWeekInYear()
{
    $time = Carbon::now()->yesterday();
    return $time->weekYear() . $time->weekOfYear;
}

function hc($amount, $price = false)
{
    if (!$price) {
        $price = Account::getCoinPrice('hc');
    }
    return getBcRound($amount * 0.7 / $price, 2);
}

function dnat($amount, $price = false)
{
    $price = $price ?: 0.2;
    return getBcRound($amount * 0.3 * 3 * 0.0005 / $price, 2);
}

function qc($income)
{
    return getBcRound($income * 0.7 + $income * 0.3 * 3 * 0.0005, 2);
}

function todayIsSunday()
{
    return Carbon::now()->dayOfWeek == 0;
}

function getBcRound($number, $precision = 0)
{
    $precision = ($precision < 0)
        ? 0
        : (int) $precision;
    if (strcmp(bcadd($number, '0', $precision), bcadd($number, '0', $precision + 1)) == 0) {
        return bcadd($number, '0', $precision);
    }
    if (getBcPresion($number) - $precision > 1) {
        $number = getBcRound($number, $precision + 1);
    }
    $t = '0.' . str_repeat('0', $precision) . '5';
    return $number < 0
        ? bcsub($number, $t, $precision)
        : bcadd($number, $t, $precision);
}

function getBcPresion($number)
{
    $dotPosition = strpos($number, '.');
    if ($dotPosition === false) {
        return 0;
    }
    return strlen($number) - strpos($number, '.') - 1;
}
